import axios from "axios";
import { ElMessage } from "element-plus";
import router from '@/router/index';

//创建axios实例对象
const request = axios.create({
  baseURL:'/api',
  timeout: 600000
})

//axios的请求,request 拦截器
request.interceptors.request.use(
  (config)=>{
      const loginUserStr =  localStorage.getItem('loginUser');
      if(loginUserStr){
        config.headers.token = JSON.parse(loginUserStr).token;
      }
      return config;
    },
  (error)=>{
    return Promise.reject(error);
  }
)

//axios的响应,response 拦截器
request.interceptors.response.use(
  (response)=>{//成功回调
    return response.data;
  },
  (error) =>{
    if(error.response.status == 401){
      ElMessage.error('用户未登录,请登录后再访问!')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default request;